﻿using B.S.Base.Write.API.Application.Command;
using MediatR;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class UpdateMenuCommandHandLer : IRequestHandler<UpdateMenuCommand, APIResult<object>>
    {
        private readonly IBaseRepostiy<MenuModel> menu;

        public UpdateMenuCommandHandLer(IBaseRepostiy<MenuModel> menu)
        {
            this.menu = menu;
        }
        public Task<APIResult<object>> Handle(UpdateMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = ResultCode.Ok ;
            result.Message = ResultCode.Ok.ToString();

            var count = menu.GetAll().Where(x => x.MenuName == request.MenuName && x.Pid == request.Pid && x.Id != request.Id && x.IsDeleted == false).Count();
            if (count > 0)
            {
                result.Code = ResultCode.Fail;
                result.Message = "修改失败，同一级菜单下名称不能重复";
                result.Data = "修改失败";
            }
            else
            {
                result.Data = "菜单修改成功";
                var entity = menu.GetAll().FirstOrDefault(x => x.Id == request.Id);
                if (entity != null)
                {
                    entity.MenuName = request.MenuName;
                    entity.Url = request.Url;
                    entity.Pid = request.Pid;
                    entity.UpdateUserName = request.UpdateUserName;
                    entity.UpdateUserTime = DateTime.Now;
                    if (request.Pid == 0)
                    {
                        entity.PmenuName = "";
                    }
                    else
                    {
                        int id = menu.GetAll().Select(x => x.Id).FirstOrDefault(x => x == request.Pid);
                        entity.PmenuName = menu.GetAll().FirstOrDefault(x => x.Id == id).MenuName;
                    }
                    menu.Update(entity);
                }
            }
            return Task.FromResult(result);
        }
    }
}
